package nameless.aistudy.domain.service.subjects.english.vocabulary;


import nameless.aistudy.domain.model.subjects.english.vocabulary.book.VocabularyBook;
import nameless.aistudy.domain.model.subjects.english.vocabulary.book.VocabularyBookRepo;
import nameless.aistudy.domain.model.subjects.english.vocabulary.dto.VocabularyBookDTO;
import nameless.aistudy.domain.model.subjects.english.vocabulary.dto.WordDetailDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

//词汇模块专用服务层
@Service
public class VocabularyService {

    @Autowired
    private VocabularyBookRepo vocabularyBookRepo;

    public VocabularyBookDTO getVocabularyBookDetails(Integer bookId) {
        // 1. 查询词汇本名称（按需扩展）


        // 2. 查询原始数据（可能包含重复单词）
        List<WordDetailDTO> rawWords = vocabularyBookRepo.getWordsByBookId(bookId);

        // 3. 按单词ID聚合，去重并合并数据
        Map<Integer, WordDetailDTO> mergedMap = new HashMap<>();
        for (WordDetailDTO word : rawWords) {
            if (mergedMap.containsKey(word.getWordId())) {
                // 已有记录，合并词性和例句（取第一个非空值）
                WordDetailDTO existing = mergedMap.get(word.getWordId());
                // 合并词性
                if (existing.getCategory() == null) {
                    existing.setCategory(word.getCategory());
                }
                // 合并例句
                if (existing.getBriefDefinitions() == null) {
                    existing.setBriefDefinitions(word.getBriefDefinitions());
                }
            } else {
                // 新记录，直接加入
                mergedMap.put(word.getWordId(), word);
            }
        }

        // 4. 转换为有序列表
        List<WordDetailDTO> mergedWords = new ArrayList<>(mergedMap.values());

        // 5. 组装最终 DTO
        VocabularyBookDTO dto = new VocabularyBookDTO();
        dto.setBookId(bookId);
//        dto.setBookName(bookName);
        dto.setWords(mergedWords);

        return dto;
    }

    public String getBookName(Integer bookId) {
        return vocabularyBookRepo.getBookName(bookId);
    }

    public List<VocabularyBook> getAllVocabularyBooks() {
        return vocabularyBookRepo.getAllVocabularyBooks();
    }
}
